package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.seach.SearchConstants;
import com.heima.model.search.dto.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    EsService<SearchArticleVO> esService;

    @Value("${file.minio.readPath}")
    String readPath;
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDTO dto) {
        //- 在搜索微服务中进行检索，查询的是es库，展示文章列表，需要根据关键字进行查询
        //- 在搜索的时候，用户输入了关键字，需要对当前用户记录搜索历史\
        //关键字不能为空
        if (dto.getSearchWords() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请输入搜索关键字");
        }
        //最小时间为空,给他设置默认值为当前时间
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            dto.setLoginUserId(user.getId());
        }
        apUserSearchService.insert(dto);
        //创建查询条件执行查询
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //构建查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //根据关键字进行查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
        //根据发布时间小于最小时间进行查询
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        builder.query(boolQueryBuilder);
        //设置查询条数
        builder.size(dto.getPageSize());
        //根据发布时间进行降序排序
        builder.sort("publishTime", SortOrder.DESC);

        //设置高亮三要素
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置高亮的字段
        highlightBuilder.field("title");
        //设置高亮的左标签
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        //设置高亮的右标签
        highlightBuilder.postTags("</font>");

        builder.highlighter(highlightBuilder);

        PageResponseResult result = esService.search(builder, SearchArticleVO.class, SearchConstants.ARTICLE_INDEX_NAME);
        List<SearchArticleVO> searchArticleVOList = (List<SearchArticleVO>) result.getData();
        for (SearchArticleVO searchArticleVO : searchArticleVOList) {
            searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
            String images = searchArticleVO.getImages();
            if (StringUtils.isNotBlank(images)) {
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                searchArticleVO.setImages(images);
            }
        }

        return result;
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        //添加到es索引库
        esService.save(article, SearchConstants.ARTICLE_INDEX_NAME);
    }

    @Override
    public void deleteArticle(String articleId) {
        //删除es索引库对应的文章信息
        esService.deleteById(articleId, SearchConstants.ARTICLE_INDEX_NAME);
    }
}